﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ClearCanvas.Dicom;
using System.IO;
using System.Threading;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
       // private string ih;
        Dictionary<string, DicomAttribute> dicomattributecolection_bygroup = new Dictionary<string, DicomAttribute>();
        DicomFile filedicom;
        DicomFile newdicomfile = new DicomFile();
        //khai bao bien de luu tat ca dicomattribute theo ong,bo cua node day
        Dictionary<string, DicomAttribute> dio = new Dictionary<string, DicomAttribute>();
        Dictionary<string, DicomAttributeCollection> dicomattributeconllection_bysequenitem = new Dictionary<string, DicomAttributeCollection>();
        DicomAttribute dicomelected;
       // string group = "";
        //khai bai bien de lay list dicomattribute bang key dua vao dicomsequence item
       
        private void button1_Click(object sender, EventArgs e)
        {
            treeView1.Nodes.Clear();
            OpenFileDialog openfiledialog = new OpenFileDialog();

            if (openfiledialog.ShowDialog() == DialogResult.OK)
            {
                filedicom = new DicomFile(openfiledialog.FileName);
                filedicom.Load();

                //DicomAttribute dicomtestvalue = filedicom.DataSet.GetAttribute(DicomTags.RoiContourSequence);
                //DicomSequenceItem[] rep = (DicomSequenceItem[])dicomtestvalue.Values;

                //DicomSequenceItem[] contourSeq = (DicomSequenceItem[])rep[0].GetAttribute(DicomTagDictionary.GetDicomTag(0x3006,0x0040)).Values;

                //string[] contourData = (string[])contourSeq[0].GetAttribute(DicomTags.ContourData).Values;
                    //int i=  filedicom.DataSet.Count;
                    foreach (DicomAttribute dicomattribute in filedicom.DataSet)
                    {
                        TreeNode node = new TreeNode();
                        //listBox1.Items.Add(dicomattribute.Values.GetType().ToString());
                        node.Text = dicomattribute.Tag.HexString.Substring(0, 4);
                        node.Name = dicomattribute.Tag.HexString.Substring(0, 4);
                        //list.Add(dicomattribute.Tag.HexString.Substring(0, 4), dicomattribute.Values.ToString());
                        if (treeView1.Nodes.Count == 0)
                        {
                            treeView1.Nodes.Add(node);
                            node.Nodes.Add("a");
                        }
                        else
                        {
                            if (treeView1.Nodes.ContainsKey(node.Name) == false)
                            {
                                treeView1.Nodes.Add(node);
                                node.Nodes.Add("a");

                            }
                        }
                    }

            }
        }



        private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            //dicomatribute_bysequence.Clear();
           // kiem tra xem node duoc chon co pai la node goc hay khong
            if (e.Node.Nodes.Count >= 1&&e.Node.Parent==null)
            {
                //group = e.Node.Text;
                e.Node.Nodes.RemoveAt(0);
                foreach (DicomAttribute dicomattribute in filedicom.DataSet)
                {
                    if (e.Node.Text.Contains(dicomattribute.Tag.HexString.Substring(0, 4))==true)
                    {
                        TreeNode newnode = new TreeNode(dicomattribute.Tag.Name);
                        newnode.Name = dicomattribute.Tag.Name;
                        if (e.Node.Nodes.ContainsKey(dicomattribute.Tag.Name) == false)
                        {
                            e.Node.Nodes.Add(newnode);

                        }//Dictionary<string, DicomAttribute> example = new Dictionary<string, DicomAttribute>()
                        if (dicomattributecolection_bygroup.ContainsKey(dicomattribute.Tag.Name) == false)
                        {
                            dicomattributecolection_bygroup.Add(dicomattribute.Tag.Name, dicomattribute);
                        }


                    }
                }
                foreach (TreeNode childennode in e.Node.Nodes)
                {
                    if (childennode.Text.Contains("Sequence") == true)
                    {
                        childennode.Nodes.Add("");
                            
                    }
                }
                
            }
           //neu chon vao node ma ten co chua sequence thi lay cai attribute tuong ung voi ten cua node do
          if (e.Node.Parent!=null&&e.Node.Text.Contains("Sequence")==true)
          {
              dicomattributeconllection_bysequenitem.Clear();
              e.Node.Nodes.Clear();
              DicomAttribute dicom = dicomattributecolection_bygroup[e.Node.Text];
              DicomSequenceItem[] dicomsequenceitem = (DicomSequenceItem[])dicom.Values;
              for (int i = 0; i < dicomsequenceitem.Length;i++ )
              {
                  TreeNode node = new TreeNode("node" + i.ToString());
                  node.Name="node"+i.ToString();
                  if (e.Node.Nodes.ContainsKey("node"+i.ToString())==false)
                  {
                      e.Node.Nodes.Add(node);
                      node.Nodes.Add("");
                      dicomattributeconllection_bysequenitem.Add("node"+i.ToString(),dicomsequenceitem[i].Copy());
                  }
              }
          } 
            // neu node duoc chon chua ten node thi lay dicomattributecollection tuong ung voi node duoc chon
            if (e.Node.Parent!=null&&e.Node.Text.Contains("node"))
            {
                //dicomattributeconllection_bysequenitem.Clear();
               try
               {
                   e.Node.Nodes.Clear();
                   DicomAttributeCollection dicomattrinutecollection = dicomattributeconllection_bysequenitem[e.Node.Text];
                   foreach (DicomAttribute dicoms in dicomattrinutecollection)
                   {
                       TreeNode papa = e.Node.Parent;
                       TreeNode papapa = papa.Parent;
                       if (dicomattributecolection_bygroup.ContainsKey(dicoms.Tag.Name) == false)
                       {
                           dicomattributecolection_bygroup.Add(dicoms.Tag.Name, dicoms);
                       }
                       if (dio.ContainsKey(e.Node.Parent+e.Node.Text+dicoms.Tag.Name)==false)
                       {
                           
                           dio.Add(papapa.Text+e.Node.Parent.Text+e.Node.Text+dicoms.Tag.Name, dicoms);
                       }
                       TreeNode newnode = new TreeNode(dicoms.Tag.Name);
                       newnode.Name = dicoms.Tag.Name;
                       if (e.Node.Nodes.ContainsKey(dicoms.Tag.Name) == false)
                       {
                           e.Node.Nodes.Add(newnode);
                           if (newnode.Text.Contains("Sequence") == true)
                           {
                               newnode.Nodes.Add("");
                           }
                       }
                   }
               }
               catch (System.Exception ex)
               {
                   e.Node.Nodes.Clear();
                   DicomAttribute dicoms = dicomattributecolection_bygroup[e.Node.Parent.Text];
                   string chuoi = e.Node.Text.ToString().Substring(4, 1);
                   int index = Convert.ToInt32(chuoi);
                   DicomAttributeCollection dicomcollection = ((DicomSequenceItem[])dicoms.Values)[index].Copy();
                   foreach (DicomAttribute dicom in dicomcollection)
                   {
                       TreeNode papa = e.Node.Parent;
                       TreeNode papapa = papa.Parent;
                       if (dio.ContainsKey(papapa.Text+e.Node.Parent.Text+e.Node.Text+dicom.Tag.Name)==false)
                       {
                           dio.Add(papapa.Text+e.Node.Parent.Text+e.Node.Text + dicom.Tag.Name, dicom);
                       }
                       TreeNode newnode = new TreeNode(dicom.Tag.Name);
                       newnode.Name = dicom.Tag.Name;
                       if (e.Node.Nodes.ContainsKey(dicom.Tag.Name)==false)
                       {
                           e.Node.Nodes.Add(newnode);
                           if (newnode.Text.Contains("Sequence")==true)
                           {
                               newnode.Nodes.Add("");
                           }
                       }
                   }
               }
            }
            
           
            // dicomattributecolection_bygroup.Clear();
            //  list[e.Node.Text];
            
          
                    
                 
            

        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {

            try
            {


                label1.Text = "";
               
                if (treeView1.SelectedNode.Parent.Text.Contains("node")==true)

                {
                    TreeNode node = treeView1.SelectedNode.Parent;
                    TreeNode papa = node.Parent;
                    TreeNode papapa = papa.Parent;
                    dicomelected = dio[papapa.Text+papa.Text+treeView1.SelectedNode.Parent.Text + treeView1.SelectedNode.Text];
                }
                if(treeView1.SelectedNode.Parent.Text.Contains("node")==false)
                {
                    dicomelected=dicomattributecolection_bygroup[treeView1.SelectedNode.Text];
                }
                  
                
                  
                if (dicomelected.Values.GetType() == typeof(string[]))
                {
                    string[] mangchuoi = (string[])dicomelected.Values;
                    for (int i = 0; i < mangchuoi.Length; i++)
                    {
                        if (i == mangchuoi.Length - 1)
                        {
                            label1.Text+= mangchuoi[i];
                        }
                        else
                        {
                            label1.Text+=mangchuoi[i]+@"\";
                        }
                    }
                }
                if (dicomelected.Values.GetType() == typeof(ushort[]))
                {
                    ushort[] mangchuoi = (ushort[])dicomelected.Values;
                    for (int i = 0; i < mangchuoi.Length; i++)
                    {
                        if (i == mangchuoi.Length - 1)
                        {
                            label1.Text += mangchuoi[i].ToString();
                        }
                        else
                        {
                            label1.Text += mangchuoi[i].ToString() + @"\";
                        }
                    }
                }
                if (dicomelected.Values.GetType() == typeof(string))
                {
                    label1.Text = (string)dicomelected.Values;
                }
                if (dicomelected.Values.GetType() == typeof(ushort))
                {
                    label1.Text = ((ushort)dicomelected.Values).ToString();
                }
                DicomSequenceItem ee;
                
            }
            catch (System.Exception ex)
            {
                label1.Text = "null";
            }

        }

       

        private void button2_Click(object sender, EventArgs e)
        {
            SaveFileDialog savefile = new SaveFileDialog();
            if (savefile.ShowDialog() == DialogResult.OK)
            {

                //tao va chay thread cho ham group 0x3006
                Thread group0x3006 = new Thread(new ThreadStart(thread_group0x0036));
                group0x3006.Start();
                //tao thread cho ham group0x008
                Thread group0x008=new Thread(new ThreadStart(thread_group0x008));
                group0x008.Start();
               //tao thread cho ham group0x0010
                Thread group0x0010=new Thread(new ThreadStart(thread_group0x0010));
                group0x0010.Start();
                //tao thread cho ham group0x0018
                Thread group0x0018 = new Thread(new ThreadStart(thread_group0x0018));
                group0x0018.Start();
                //tao thread cho ham group0x0020
                Thread group0x0020 = new Thread(new ThreadStart(thread_group0x0020));
                group0x0020.Start();
               bool kiemtra= newdicomfile.Save(savefile.FileName);
               if (kiemtra == true)
               {
                   MessageBox.Show("success");
               }
              

            }
          

        }
        private void thread_group0x008()
        {
            
            newdicomfile.DataSet[DicomTags.SpecificCharacterSet].SetString(0, "ISO_IR 100");
            newdicomfile.DataSet[DicomTags.InstanceCreationDate].SetString(0, "20120403");
        }
        private void thread_group0x0010()
        {
            newdicomfile.DataSet[DicomTags.PatientsName].SetString(0, "UNKNOWN^^^^ ");
        }
        private void thread_group0x0018()
        {
            newdicomfile.DataSet[DicomTags.SoftwareVersions].SetString(0, "1.0");
        }
        private void thread_group0x0020()
        {
            newdicomfile.DataSet[DicomTags.StudyInstanceUid].SetString(0, "1.2.840.113729.1.42977.5016.2012.4.3.9.58.58.926.3913");
        }
        private void thread_group0x0036()
        {
            try
            {
              
                 DicomSequenceItem frameReference = new DicomSequenceItem();
            newdicomfile.DataSet[DicomTags.ReferencedFrameOfReferenceSequence].SetNullValue();
            DicomAttributeSQ frameRefer = (DicomAttributeSQ)newdicomfile.DataSet[DicomTags.ReferencedFrameOfReferenceSequence];
            frameRefer.AddSequenceItem(frameReference);
            frameReference[DicomTags.FrameOfReferenceUid].SetString(0, "ff");
            frameReference[DicomTags.RtReferencedStudySequence].SetNullValue();
            DicomAttributeSQ RtReferencedStudySequence = (DicomAttributeSQ)frameReference[DicomTags.RtReferencedStudySequence];
            DicomSequenceItem item_RtReferencedStudySequence = new DicomSequenceItem();
            item_RtReferencedStudySequence[DicomTags.ReferencedSopClassUid].SetString(0, "nnegdd");
            item_RtReferencedStudySequence[DicomTags.RtReferencedSeriesSequence].SetNullValue();
            // lay dicomattributesq cua RtReferencedSeriesSequence
            DicomAttributeSQ RtReferencedSeriesSequence = (DicomAttributeSQ)item_RtReferencedStudySequence[DicomTags.RtReferencedSeriesSequence];
            // khai bao item con cua RtReferencedSeriesSequence
            DicomSequenceItem item_RtReferencedSeriesSequence = new DicomSequenceItem();

            // lay dicomattributesq cua ContourImageSequence
            DicomAttributeSQ ContourImageSequence = (DicomAttributeSQ)item_RtReferencedSeriesSequence[DicomTags.ContourImageSequence];
            // set gia value cho ContourImageSequence=null;
            ContourImageSequence.SetNullValue();
            RtReferencedSeriesSequence.AddSequenceItem(item_RtReferencedSeriesSequence);
            //chay vong for de add cac contour vao dicomattributesq khai bao item con cua ContourImageSequence
            for (int i = 0; i < 100; i++)
            {
                DicomSequenceItem item_ContourImageSequence = new DicomSequenceItem();
                item_ContourImageSequence[DicomTags.ReferencedSopClassUid].SetString(0, "nguyen van hung");
                ContourImageSequence.AddSequenceItem(item_ContourImageSequence);
            }

            RtReferencedStudySequence.AddSequenceItem(item_RtReferencedStudySequence);
            //xay dung roicontour sequence(0x0039)
            //setvalue cho no bang null
            DicomAttributeSQ RoiContourSequence = (DicomAttributeSQ)newdicomfile.DataSet[DicomTags.RoiContourSequence];
            RoiContourSequence.SetNullValue();
            //khai bao dicomsequenceitem cua dicomattribute
            for (int i = 0; i < 20; i++)
            {
                //khai bao dicomsequenceitem cho dicomattribute do
                DicomSequenceItem item_RoiContourSequence = new DicomSequenceItem();
                //set value cho dicomattribute ma ban chi dinh
                item_RoiContourSequence[DicomTags.RoiDisplayColor].SetString(0, "252");
                item_RoiContourSequence[DicomTags.ReferencedRoiNumber].SetString(0, "4");
                //lay doi tuong dicomattributesq cua contoursequence
                DicomAttributeSQ contoursequence = (DicomAttributeSQ)item_RoiContourSequence[DicomTags.ContourSequence];
                // add dicomsequnece item  vao dicomattributesq hien thoi cua ban
                RoiContourSequence.AddSequenceItem(item_RoiContourSequence);
                //set value cho dicomattribute nay la null
                contoursequence.SetNullValue();
                // khai bao dicomsequence item cho contoursequence
                for (int j = 0; j < 10; j++)
                {
                    DicomSequenceItem item_contoursequence = new DicomSequenceItem();
                    //setvalue cho dicom trong do
                    item_contoursequence[DicomTags.ContourData].SetString(0, "784699");
                    item_contoursequence[DicomTags.NumberOfContourPoints].SetString(0, "9");
                    // add dicomsequnece item vao contoursequence
                    contoursequence.AddSequenceItem(item_contoursequence);
                    //khai bao doi tuong dicomattributesq cho contourimage sequence
                    DicomAttributeSQ contourimagesequence = (DicomAttributeSQ)item_contoursequence[DicomTags.ContourImageSequence];
                    // set value cho no bang null
                    contourimagesequence.SetNullValue();
                    for (int k = 0; k < 1; k++)
                    {
                        // khai bao dicomsequence item cho dicomattributesq vua chon
                        DicomSequenceItem item_contourimagesequence = new DicomSequenceItem();
                        // setvaluse cho dicomattribute ban lua chon
                        
                        item_contourimagesequence[DicomTags.ReferencedSopClassUid].SetString(0, "1.2.840.10008.5.1.4.1.1.2");
                        item_contourimagesequence[DicomTags.ReferencedSopInstanceUid].SetString(0, "1.2.840.113729.1.42977.5016.2012.4.3.9.59.48.81.4561");
                        // add dicomsequence item vao dicomattributesq contourimagesequence
                        contourimagesequence.AddSequenceItem(item_contourimagesequence);
                    }
                }

            }

            }
            catch(Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
        



    }
}
